package com.aura.lyngen.aop;

import com.aura.lyngen.annotation.AuthCheck;
import com.aura.lyngen.exception.BusinessException;
import com.aura.lyngen.exception.ErrorCode;
import com.aura.lyngen.model.entity.User;
import com.aura.lyngen.model.enums.UserRoleEnum;
import com.aura.lyngen.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;


    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 获取注解中的权限要求
        String mustRole = authCheck.mustRole();

        // 获取当前请求的HttpServletRequest对象
        HttpServletRequest request = getHttpRequest();

        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);

        // 如果没有设置角色要求，则直接放行
        if (isRoleCheckNotRequired(mustRole)) {
            return joinPoint.proceed();
        }

        // 检查用户角色是否符合要求
        checkUserRole(mustRole, loginUser);

        // 通过权限校验，放行
        return joinPoint.proceed();
    }

    /**
     * 获取当前请求的 HttpServletRequest 对象
     */
    private HttpServletRequest getHttpRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * 判断是否不需要角色校验
     */
    private boolean isRoleCheckNotRequired(String mustRole) {
        return UserRoleEnum.getEnumByValue(mustRole) == null;
    }

    /**
     * 检查用户角色是否符合要求
     */
    private void checkUserRole(String mustRole, User loginUser) {
        // 获取用户角色枚举
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        if (mustRoleEnum == null) {
            return; // 如果没有角色要求，直接放行
        }

        // 获取当前用户的角色
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());

        // 判断当前用户角色是否为空，若为空则抛出权限错误
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.ROLE_NOT_FOUND, "用户角色为空");
        }

        // 判断当前用户角色是否符合要求
        if (!userRoleEnum.equals(mustRoleEnum)) {
            throw new BusinessException(ErrorCode.PERMISSION_DENIED, "用户没有足够的权限");
        }
    }


}
